package cn.tedu.stx_admin.config;

import cn.tedu.stx_admin.filter.JwtAuthorizationFilter;
import cn.tedu.stx_common.enumerator.ServiceCode;
import cn.tedu.stx_common.web.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.io.PrintWriter;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Autowired
    private JwtAuthorizationFilter jwtAuthorizationFilter;

    // 密码加密
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
    // 认证管理器
    @Bean
    public AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 关闭session
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        // 将自定义的解析JWT的过滤器添加到Security框架的过滤器链中
        http.addFilterBefore(jwtAuthorizationFilter, UsernamePasswordAuthenticationFilter.class);
        // 关闭伪造的跨域访问攻击防御
        http.csrf().disable();
        // Security允许跨域访问
        http.cors();

        // 白名单
        String[] urls={
                "/doc.html",
                "/**/*.css",
                "/**/*.js",
                "/swagger-resources",
                "/v2/api-docs",
                "/test/permit",
                "/admin/add-admin",    // 后期要添加jwt验证才能注册
                "/admin/login"
        };
        http.authorizeRequests().mvcMatchers(urls).permitAll().anyRequest().authenticated();
        // 处理未登录
        http.exceptionHandling().authenticationEntryPoint((request, response, e) -> {
            String message="你还没有登录，请登录！";
            JsonResult jsonResult=JsonResult.fail(ServiceCode.ERR_JWT_MALFORMED,message);
            PrintWriter writer = response.getWriter();
            writer.println(JSON.toJSONString(jsonResult));
            writer.close();
            return;
        });

    }

}
